#ifndef __KEYHANDING_H__
#define __KEYHANDING_H__

#include <cstdio>
#include <termios.h>
#include <unistd.h>

/**
 * @brief 按键枚举
 *
 */
typedef enum {
  KEYPRESS_EMPTY = 0,
  KEYPRESS_BLANK, /// 空格
  KEYPRESS_W,     /// 上
  KEYPRESS_S,     /// 下
  KEYPRESS_A,     /// 左
  KEYPRESS_D,     /// 右
  KEYPRESS_Q,     /// 退出
} KEYPRESS;

/**
 * @brief 按键
 *
 */
class KeyHanding {
private:
public:
  KeyHanding() {
    struct termios attr;
    tcgetattr(0, &attr);              //获取属性
    attr.c_lflag &= ~(ICANON | ECHO); //关闭回车确认和回显
    tcsetattr(0, TCSANOW, &attr);     //设置属性
  }
  ~KeyHanding() {
    struct termios termios;
    tcgetattr(0, &termios);
    termios.c_lflag |= (ECHO | ICANON);
    // TCSANOW the change occurs immediately
    tcsetattr(0, TCSANOW, &termios);
  }

  KEYPRESS KeyHandingVal(void) {
    char c = getchar();
    KEYPRESS keypress = KEYPRESS_EMPTY;
    switch (c) {
    case 'W':
    case 'w':
      keypress = KEYPRESS_W;
      break;
    case 'S':
    case 's':
      keypress = KEYPRESS_S;
      break;
    case 'A':
    case 'a':
      keypress = KEYPRESS_A;
      break;
    case 'D':
    case 'd':
      keypress = KEYPRESS_D;
      break;
    case ' ':
      keypress = KEYPRESS_BLANK;
      break;
    case 'Q':
    case 'q':
      keypress = KEYPRESS_Q;
      break;
    default:
      keypress = KEYPRESS_EMPTY;
      break;
    }
    return keypress;
  }
};

#endif // __KEYHANDING_H__